import { FileStorage, BaseModel } from '../utils/fileStorage';
import bcrypt from 'bcryptjs';

export interface User extends BaseModel {
  username: string;
  password: string;
  role: 'admin' | 'user';
}

export interface CreateUserData {
  username: string;
  password: string;
  role?: 'admin' | 'user';
}

export class UserModel {
  private static storage = new FileStorage<User>('users.json');

  // 检查是否存在管理员账号
  static async hasAdmin(): Promise<boolean> {
    return this.storage.count(user => user.role === 'admin') > 0;
  }

  // 创建用户
  static async create(userData: CreateUserData): Promise<number> {
    const { username, password, role = 'user' } = userData;
    const hashedPassword = await bcrypt.hash(password, 10);

    return this.storage.create({
      username,
      password: hashedPassword,
      role
    });
  }

  // 通过用户名查找用户
  static async findByUsername(username: string): Promise<User | null> {
    const user = this.storage.findOne(user => user.username === username);
    return user || null;
  }

  // 验证密码
  static async verifyPassword(user: User, password: string): Promise<boolean> {
    return bcrypt.compare(password, user.password);
  }

  // 更新用户
  static async update(id: number, data: Partial<User>): Promise<boolean> {
    // 如果要更新密码，需要先加密
    if (data.password) {
      data.password = await bcrypt.hash(data.password, 10);
    }
    return this.storage.update(id, data);
  }
} 